<template>
	<view>
		<view style="width: 100%;height: 100%;" v-if="reloadFlag">
			<view class="ing" v-if="ingFlag" @tap.stop>
				<image src="../../static/ing.png" mode=""></image>
			</view>
			<baTreePicker ref="treePicker" :multiple='false' @select-change="selectChange" title="请选择"
				:localdata="deptUserList" :selectParent="false" valueKey="value" textKey="text" childrenKey="children" style="position: relative;z-index: 9;"></baTreePicker>
			<view class="detailForm">
				<view class="topBottomBox">
					<view class="detailItem" v-if="false">
						<view class="detailLabel">
							点位：
						</view>
						<picker mode="selector" class="detailInput" v-model="pointIndex" :range="pointList.map(item=>item.label)" @change="changePointer">
							<view class="picker">
								{{(Number(pointIndex)>-1)
									?pointList.map(item=>item.label)[pointIndex] || '请选择'
									:'未选择'
								}}
							</view>
						</picker>
					</view>
					<view class="detailItem" style="border-bottom: none;">
						<view class="detailLabel">
							发送至：
						</view>
						<input disabled="disabled" class="detailInput" @click="showPicker" v-model="userName" style="border-bottom:1px solid #DCDFE6;"/> 
						<!-- <superweicombox style="margin-top: 12rpx;" class="detailInput" :candidates="userList" :isJSON="true" keyName="realname" placeholder="请输入选择"
							v-model="userText" @input="input_json" @select="select_json"></superweicombox> -->
						<!-- <picker mode="selector" class="detailInput" v-model="userIndex" :range="userList.map(item=>item.realname)" @change="changeUser">
							<view class="picker">
								{{(Number(userIndex)>-1)
									?userList.map(item=>item.realname)[userIndex] || '请选择'
									:'未选择'
								}}
							</view>
						</picker> -->
					</view>
				</view>
				<view class="topBottomBox">
					<view class="h3">异常处理(安全观察与沟通)</view>
					<view class="erItem" v-for="(error,index) in errorList" :key=index>
						<view class="erItemLabel" >
							<span>问题项{{index+1}}：</span>
							<span style="float:right;color: #FF4F37;" @click="deleteError(index)"> 删除</span>
						</view>
						<!-- <input :disabled="cardWarn"  type="text" v-model="cardId" class="detailInput" placeholder="请输入卡ID"/> -->
						<textarea style="min-height: 76rpx;max-height: 210rpx;form-sizing: normal;width: 100%;overflow-y: auto;resize: none;background: #F3F4F9;width: 100%;flex-shrink: 0;" type="text" v-model="error.issueDesc" class="detailInput" placeholder="请输入问题描述"/>
					</view>
					<view style="color: #505050;font-weight: bold;margin-top: 40rpx;" @click="addErrorItem()">新增问题项</view>
					<view style="display: flex;justify-content: space-around;border-bottom: none;gap:12px ;">
						<view class="subBtn" :style="(errorStatus=='待处理'?'background:#13CA9C;':'')+'padding:0;width:100%;text-align:center;'"  @click="changeErrorStatus('待处理')">
							待处理(需反馈)
						</view>
						<view class="subBtn" :style="(errorStatus=='已解决'?'background:#13CA9C;':'')+'padding:0;width:100%;text-align:center;'"  @click="changeErrorStatus('已解决')">
							已处理(无需反馈)
						</view>
					</view>
					<view>
						<view class="detailLabel" >
							处理意见:
						</view>
						<!-- <input :disabled="cardWarn"  type="text" v-model="cardId" class="detailInput" placeholder="请输入卡ID"/> -->
						<textarea style="width: 100%;" v-model="handOpinions" type="text" value="" class="detailInput"></textarea>
					</view>
					<view class="btns">
						<view class="blueBtn" style="width: 100%;text-align: center;" @click="subData()">提交</view>
					</view>
				</view>
				
			</view>
		</view>
		
		
	</view>
</template>

<script>
	import superweicombox from "@/components/superwei-combox/components/superwei-combox/superwei-combox.vue"
	import { ACCESS_TOKEN,USER_NAME,USER_INFO } from "@/common/util/constants"
	import baTreePicker from "@/components/ba-tree-picker/ba-tree-picker.vue"
	export default {
		name:'respectIng',
		components:{superweicombox,baTreePicker},
		props:{
			taskId:String,
			taskName:String,
			itemId:String,
			lineId:String,
			pointId:String,
			cardId:String,
			cardName:String,
			cardNo:String,
			// value: { // 当前显示的下标 (使用v-model语法糖: 1.props需为value; 2.需回调input事件)
			// 	type: [String, Number],
			// 	default(){
			// 		return 0
			// 	}
			// },
			// fixed: Boolean // 是否悬浮,默认false
		},
		data() {
			console.log({
				taskId:this.taskId,
				itemId:this.itemId,
				lineId:this.lineId,
				pointId:this.pointId,
				cardId:this.cardId,
				cardName:this.cardName,
				cardNo:this.cardNo,
			})
			return {
				reloadFlag:true,
				ingFlag:false,
				candidates_json:[{
					id: '1',
					name: '选项一'
				}, {
					id: '2',
					name: '选项二',
					disabled: true // 单独设置disabled后即可禁用该选项
				}, {
					id: '3',
					name: '选项三'
				}],
				userText:'',
				userList:[],
				deptUserList:[],
				deptList:[],
				userName:'',
				userCodeName:'',//当前人账号
				userIndex:-1,
				pointIdCurrent:this.pointId,
				NFCAdapter:null,
				// cardId:'',//卡ID 165516514561651sad6R515
				// cardNo:'',//卡号 4d45e29a
				// cardName:'',//卡名称 YP0001X
				actionPage:'sub',// wait sub
				selected:'2',
				remark:'',
				selectStatusFlag:false,
				status:'',
				cardWarn:true,//是否允许编辑
				pointList:[],//点位列表，异常时候可以手动选择
				pointName:'',
				pointIndex:-1,
				speStatus:'normal',//normal:卡片状态正常  error:卡片状态异常
				errorStatus:'待处理',
				errorList:[{}],
				handOpinions:'',//整体异常处理意见
			}
		},
		async mounted() {
			// this.closeNfc();
			// 获取点位列表
			await this.getPoints();
			await this.getUserList()
			// 开始识别卡片
			// if(!this.NFCAdapter){
			// 	console.log('没有初始化就进来')
			// 	this.actionCheck();
			// }
			
			// 暂时默认写死,之后在读取卡ID之后触发
			// this.getCardInfo();
		},
		methods: {
			// 显示人员选择器
			showPicker() {
				let piker = this.$refs.treePicker;
				piker.showDialog?piker._hide():piker._show();
			},
			input_json(e) {
				console.log('下拉输入',e) // 选项一
			},
			select_json(e) {
				console.log('json下拉',e) // {id: '1',name: '选项一'}
				console.log(this.userText);
				this.userName = e.realname
				this.userCodeName = e.username
				this.userId = e.id
			},
			changeErrorStatus(val){//更改问题状态
				this.errorStatus=val;
			},
			addErrorItem(){
				this.errorList.push({})
			},
			deleteError(index){
				this.errorList.splice(index,1)
			},
			addErrorSub(){
				let _this = this;
				console.log('用户信息',uni.getStorageSync(USER_INFO))
				let time = new Date();
				let YY = time.getFullYear();
				let MM = time.getMonth();
				let DD = time.getDate();
				let current = YY+'-'+(MM+1)+'-'+DD
				let courseList=[{
					unusualInitiatorId:uni.getStorageSync(USER_INFO).username,//发起人
					unusualRecipientId:uni.getStorageSync(USER_INFO).username,//当前责任人
					status:'2',//状态 0:暂停 1处理中；2已解决,
					remark:this.handOpinions//处理意见
				}];
				if(this.errorStatus=='待处理'){
					courseList.push({
						unusualInitiatorId:uni.getStorageSync(USER_INFO).username,//发起人
						unusualRecipientId:this.userCodeName,//当前责任人
						status:'1',//状态 0:暂停 1处理中；2已解决,
						remark:''//处理意见
					})
				}
				this.ingFlag = true;
				this.$http.post('/inspect/insClassesUnusualMsg/add',{
					unusualName:uni.getStorageSync(USER_INFO).realname+'于'+current+' 发起的问题',//异常标题
					unusualContent:this.remark,//异常内容
					taskId:this.taskId,//任务ID,
					pointId:this.pointIdCurrent,//点位ID
					courseList:courseList,//指派给
					status:this.errorStatus=='待处理'?'1':'2',//状态 1处理中；2已解决,
					issueList:this.errorList //问题项
				}).then(res=>{
					_this.ingFlag = false;
					if(res.data.success){
						_this.$tip.toast('提交成功');
						_this.handOpinions = "";
						_this.userName='';
						_this.userCodeName='';
						_this.$set(_this,"errorList",[{}]);
						_this.pointIndex = -1;
						_this.userIndex = -1;
					}else{
						_this.$tip.toast(res.data.message);
					}
					console.log(res);
				})
			},
			//监听选择（ids为数组）
			selectChange(ids, names) {
				console.log(ids, names);
				this.userName=names;
				this.userCodeName=ids[0];
			},
			async getUserList(){
				let _this = this;
				await this.$http.get('/sys/dict/getDictItems/sys_depart,depart_name,org_code').then(res=>{
					_this.deptList=res.data.result;
				})
				await this.$http.get('/sys/user/list?pageNo=1&pageSize=9999').then((res)=>{
					_this.userList = res.data.result.records;
				})
				let users = JSON.parse(JSON.stringify(_this.userList))
				_this.deptUserList = _this.deptList.map(item=>{
					return {
						...item,
						children:users.filter(ii=>{
							if(ii.orgCode){
								return ii?.orgCode.split(',').some(tt=>{
									return tt == item.value
								})
							}else{
								return false;
							}
						}).map(ee=>{return {
							...ee,
							value:ee.username,
							text:ee.realname
						}})
					}
				})
			},
			cardWarnSpe(){
				this.actionPage = 'sub';
				this.speStatus = 'error'
			},
			closeNfc(){
				if(this.NFCAdapter){
					console.log('开始清除')
					this.NFCAdapter.offDiscovered(this.discoverHandler)
					this.NFCAdapter.stopDiscovery()
					this.NFCAdapter = null
					console.log('清除结束')
				}
			},
			async getPoints(){
				let _this = this;
				await this.$http.get('/inspect/insPoint/list?pageNo=1&pageSize=9999')
					.then(res=>{
						if(res.data.success){
						 _this.pointList = res.data.result.records.map(item=>{
							 return {
								 value:item.id,
								 label:item.pointName
							 }
						 })
						}
					})
			},
			changePointer(val){
				this.pointIndex = val.detail.value
				this.pointIdCurrent = this.pointList[val.detail.value].value
			},
			changeUser(val){
				this.userIndex = val.detail.value
				this.userName = this.userList[val.detail.value].realname
				this.userCodeName = this.userList[val.detail.value].username
				this.userId = this.userList[val.detail.value].id
			},
			changeStatus(val){
				let obj=['','正常','异常']
				this.status = obj[val];
				this.selectStatusFlag = false;
				if(val == '1'){
					this.subData()
				}
			},
			getCardInfo(id){
				let _this = this;
				this.$http.get('/inspect/insPoint/queryByCardNo',{
					params:{cardNo:id || this.cardNo }
				}).then(res=>{
					if(res.data.success){
						_this.cardId = res.data.result.cardId;
						_this.cardName = res.data.result.cardName || res.data.result.cardNo || '异常';
						let zindex=-1;
						_this.pointList.forEach((ii,index)=>{
							if(ii.label == res.data.result.pointName){
								zindex = index
							}
						})
						_this.pointIndex = zindex
						_this.pointIdCurrent = _this.pointList[zindex].value
						console.log('回填：',_this.pointIndex)
					}else{
						_this.$tip.toast(res.data.message);
						_this.actionPage = 'wait'
					}
					
					console.log('卡的详细信息1',res)
				})
			},
			selectStatus(){
				this.selectStatusFlag = !this.selectStatusFlag;
			},
			subData(){
				let _this = this;
				if(this.errorStatus=='待处理'&& !(this.userCodeName)){
					return this.$tip.toast('请选择指派人！');
				}
				let statusObj = {
					lineId : this.lineId,
					pointId : this.pointIdCurrent,
					itemId : this.itemId,
					taskId : this.taskId,
					insStatus:this.status=="正常"?'1':'2',
					remark:this.remark,
					userId:this.userId,
					userPhone:''
				};
				if(this.userList && this.userList.length){  
					var userC = this.userList.filter(item=>{return item.id == this.userId});
					if(userC.length){
						statusObj.userPhone = userC[0].phone
					}
					
				}
				if(this.speStatus == 'normal'){
					statusObj.cardId=this.cardId;
					statusObj.cardNo=this.cardNo;
				}
				console.log(statusObj)
				// if( !statusObj.pointId){
				// 	return this.$tip.toast('请选择点位')
				// }
				// if(!statusObj.insStatus){
				// 	return this.$tip.toast('请选择状态')
				// }
				// if( statusObj.insStatus == '2' && !statusObj.remark){
				// 	return this.$tip.toast('请填写异常备注！')
				// }
				if(this.errorList.length<=0 || this.errorList.some(item=>{return !(item.issueDesc)})){
					return this.$tip.toast('请完成问题项的描述')
				}
				this.addErrorSub();
			},
			change(val){
				console.log(val)
			},
			actionCheck(){
				this.$tip.alert("请将设备放入识别区NFC")
				console.log(this.NFCAdapter);
				try{
					this.closeNfc();
				}catch(e){
					//TODO handle the exception
				}
				this.NFCAdapter = wx.getNFCAdapter();
				this.NFClistener();
			},
			NFClistener(){
				let _this = this;
				this.NFCAdapter.startDiscovery({
				  success: () => {
				    _this.$tip.alert("请将设备放入识别区NFC")
				    // 监听 NFC 标签
				    _this.NFCAdapter.onDiscovered(this.discoverHandler)
				  },
				  fail: error => {
					  console.log('error',error)
					  if(error.errMsg=='startDiscovery:fail:NFC discovery already started'){
						  _this.NFCAdapter.onDiscovered(this.discoverHandler)
					  }
						// _this.$tip.alert("请重试")
				    console.error(error)
				  }
				})
			},
			/**
			 * 监听回调
			 */
			discoverHandler(callback) {
				let _this = this;
			  console.log('==================== START ====================')
			  console.log('onDiscovered callback=>', callback)
			  let arr = [0x01, 0x01, 0x01, 0x01];
				let writeBuffer = new Uint8Array(arr);
				 let cId = this.changeType(callback.id)
				_this.cardNo = cId || ''
				// setTimeout(function(){
					_this.actionPage = 'sub'
				// },100)
				
				// 通过id获取对应的卡片信息以及卡片绑定的点位信息
				_this.getCardInfo(cId);
			},
			changeType(buffer){
			 return Array.prototype.map.call(new Uint8Array(buffer),x => ('00'+x.toString(16)).slice(-2)).join('')
			},
		}
	}
</script>

<style scoped>
	.beforeSpeBox{
		width: 100vw;
		height: 90vh;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		position: relative;
	}
	.errorBox{
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		bottom: 12px;
		font-size: 12px;
		color: rgba(102, 102, 102, 1);
	}
	.beforeSpe{
		height: 20px;
		background-color: #0081FF;
		border-radius: 6px;
		animation:fullWidth 3s linear infinite;
		margin-bottom: 12px;
	}
	@keyframes fullWidth{
		from{
			width:0px
		}
		to{
			width: 200px;
		}
	}
	.detailLabel{
		display: flex;
		justify-content: space-between;
	}
	.topBottomBox{
		background: #fff;
		border-radius: 6px;
		padding: 12px;
		margin: 0 12px;
		margin-top: 12px;
	}
	.detailForm{
		width: 100%;
		height: 100vh;
		background-color: #fff;
		border-radius: 8px;
		box-shadow: 0px 0px 5px rgba(0,0,0,.1);
		padding: 0;
		font-size: 13px;
		line-height: 38px;
		padding-bottom: 100px;
		overflow: auto;
		background-image: linear-gradient(to bottom,#DEF6ED,#F5F7F9);
	}
	.btns{
		position: absolute;
		bottom: 40px;
		left: 24rpx;
		right: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 52px;
		margin-top: 50px;
		
	}
	.btns>view{
		box-shadow: 0px 0px 16px rgba(19, 202, 156, 0.44);
	}
	.blueBtn{
		padding: 0 22px;
		border-radius: 4px;
		line-height: 30px;
		display: inline-block;
		color: #fff;
		font-size: 14px;
		background-color: #13CA9C;
	}
	.selectBox{
		width: 160px;
		max-height: 150px;
		overflow: auto;
		border-radius: 4px;
		box-shadow: 0 0 5px rgba(0,0,0,.1);
		background: #fff;
		position: absolute;
		z-index: 222;
		top: 43px;
		left: 60px;
	}
	.selectItem{
		border-bottom: 1px solid rgba(0,0,0,.02);
		line-height: 30px;
		padding-left: 12px;
	}
	.detailLabel{
		width: 160rpx;
		flex-shrink: 0;
		color: #000000;
	}
	.detailInput{
		width: calc(100% - 160rpx);
		height: 38px;
		color: #555;
		font-size: 12px;
	}
	textarea.detailInput{
		height: 80px;
		line-height: 20px;
		border: 1px solid rgba(0,0,0,.1);
		border-radius: 2px;
		margin-top: 6px;
		padding: 6px;
	}
	.detailItem{
		border-bottom: 1px solid rgba(0,0,0,.04);
		display: flex;
		position: relative;
	}
	.waitCheck,.box{
		width:100%;
		height: 100%;
	}
	.waitCheck{
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
	}
	.h3{
		font-weight: bold;
		font-size: 18px;
	}
	.labelPla{
		color: #999;
		font-size: 14px;
	}
	.warnTbn{
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		bottom: 12px;
		font-size: 10px;
		color: #666;
	}
	.utton{
		background-color: #0081FF;
		border-radius: 3px;
		height: 32px;
		line-height: 32px;
		padding: 0 12px;
		color: white;
		font-size: 16px;
	}
	.subBtn{
		box-shadow:inset 1px 1px 1px 0px rgba(255, 255, 255, 0.8), inset -1px -1px 1px 0px rgba(40, 49, 85, 0.3), 1px 1px 3px 0px rgba(40, 49, 85, 0.1);
		text-shadow: 1px 1px 1px rgba(0,0,0,.1);
		line-height: 32px;
		border-radius: 4px;
		margin:30px 0;
		padding: 0 50px;
	}
	.erItemLabel{
		display: flex;
		justify-content: space-between;
	}
	.ing{
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: rgba(255,255,255,.7);
		z-index: 999;
	}
	.ing image{
		width: 80rpx;
		height: 80rpx;
		animation:rotateFunc 1s linear infinite;
		transform-origin: center;
	}
	@keyframes rotateFunc{
		from{
			transform:rotate(0deg) ;
		}
		to{
			transform: rotate(360deg);
		}
	}
</style>
